import { sp } from "@pnp/sp/presets/all";
import { WebPartContext } from "@microsoft/sp-webpart-base";

// 定义列表项接口
interface IListItem {
  Id: number;
  Title: string;
  // 添加其他列表字段
  [key: string]: unknown;
  
  // 附件URL数组
  attachmentUrls?: string[];
}

export async function fetchSharePointListData(listName: string, context: WebPartContext): Promise<IListItem[]> {
  try {
    sp.setup({
      sp: {
        baseUrl: "https://zhi1soft.sharepoint.cn/sites/aiSquare",
        headers: {
          Accept: "application/json"
        }
      }
    });

    // 获取所有列表项
    const items: IListItem[] = await sp.web.lists.getById(listName).items.get();
    console.log("Fetched list items:", items);
    
    // 为每个列表项获取附件
    const itemsWithAttachments = await Promise.all(
      items.map(async (item) => {
        const newItem = { ...item }; // Create a new object to avoid race conditions
        try {
          // 获取当前项的附件
          const attachments = await sp.web.lists.getById(listName)
            .items.getById(item.Id)
            .attachmentFiles();
          
          // 如果有附件，则获取URL
          if (attachments && attachments.length > 0) {
            // 构建完整的附件URL
            const siteUrl = "https://zhi1soft.sharepoint.cn";
            const attachmentUrls = attachments.map(attachment => 
              `${siteUrl}${attachment.ServerRelativeUrl}`
            );
            
            // 将附件URL添加到列表项中
            newItem.attachmentUrls = attachmentUrls;
          } else {
            newItem.attachmentUrls = [];
          }
          return newItem;
        } catch (error) {
          console.error(`获取项 ${item.Id} 的附件失败:`, error);
          newItem.attachmentUrls = [];
          return newItem;
        }
      })
    );
    
    console.log("Items with attachment URLs:", itemsWithAttachments);
    return itemsWithAttachments;
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
}



